package com.example.service.impl;

import com.example.dao.UserMapper;
import com.example.domain.User;
import com.example.entity.PageResult;
import com.example.service.UserService;
import com.example.utils.SHA256Util;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {


    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(User user) {
        if(user.getPassword()!=null) {
            user.setPassword(SHA256Util.getCode(user.getPassword()));
        }
        return userMapper.findUserByEmailAndPassword(user);
    }

    @Override
    public Integer addUser(User user) {
        if(user.getPassword()!=null) {
            user.setPassword(SHA256Util.getCode(user.getPassword()));
        }
        return userMapper.addUser(user);
    }

    @Override
    public PageResult findAllUsers(Integer pageNum, Integer pageSize, Integer userId) {
        //  开启分页
        PageHelper.startPage(pageNum, pageSize);
        Page<User> users = userMapper.findAllUsers(userId);
        return new PageResult(users.getTotal(), users.getResult());

    }

    @Override
    public PageResult search(User user, Integer pageNum, Integer pageSize) {
        if(user.getPassword()!=null) {
            user.setPassword(SHA256Util.getCode(user.getPassword()));
        }
        //  开启分页
        PageHelper.startPage(pageNum, pageSize);

        //  调用 Mapper 查询
        Page<User> users = userMapper.searchUsers(user);

        //  封装返回结果
        return new PageResult(users.getTotal(), users.getResult());
    }

    @Override
    public Integer editUser(User user) {
        if(user.getPassword()!=null) {
            user.setPassword(SHA256Util.getCode(user.getPassword()));
        }
        return userMapper.editUser(user);
    }

    @Override
    public User findUserById(String id) {
        return userMapper.findUserById(id);
    }


}
